%% ex5.m
% set dir: src/
close all;
clear; clc;

%% Test Sector
w = gaussKernel(60,500);
figure(Position=[100,100,900,500])
subplot(1,2,1)
mesh(w)
xlim([0,501])
ylim([0,501])
colorbar('south')
subplot(1,2,2)
plot(w(250,:))
legend('w(250,:)')
xlim([0,501])

%% gaussKernel
function w = gaussKernel(sig, m)
% Generate Gaussian kernel using given sigma and size.
% - Input
% sig(numeric): input grayscale matrix.
% m(numeric): convolution kernel.
% w(matrix): generated Gaussian Kernel

% If m is not provieded, calculate a properate m.
if nargin < 2
    m = ceil(6 * sig) + 1;
end

% If m is even, make it singular.
if mod(m, 2) == 0
    m = m + 1;
end

% If m is too small, throw a warning.
minSize = ceil(6 * sig) + 1;
if m < minSize
    warning('Provided m is too small.');
end

center = (m - 1) / 2;

% compute Gaussian function
w = zeros(m, m);
for i = 1:m
    for j = 1:m
        x = i - center - 1;
        y = j - center - 1;
        w(i, j) = exp(-(x^2 + y^2) / (2 * sig^2));
    end
end

% normalize Gaussian Kernel
w = w / sum(w(:));
end